package com.kaifamiao.filter;

import org.tinylog.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "dispatcher-filter",
           urlPatterns = "/*",
           dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE } )
public class DispatcherFilter implements Filter {

    private String name ;

    @Override
    public void init(FilterConfig config) throws ServletException {
        name = config.getFilterName();
        Logger.trace("初始化【{}】过滤器", name );
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response= (HttpServletResponse)resp;
        // 获取请求调度类型
        DispatcherType type = request.getDispatcherType();
        // 获取本次请求所访问的资源路径
        String uri = request.getRequestURI();
        Logger.trace("【{}】调度类型: {}, 被访问资源的路径: {}", name, type, uri );

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

}
